package vip.specimen.system.common.implement;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import vip.specimen.system.common.connector.SaveMethodInterface;
import vip.specimen.system.common.enums.ResultCode;
import vip.specimen.system.common.enums.SaveMethodEnum;
import vip.specimen.system.common.handler.SystemExceptionHandler;
import vip.specimen.system.datasource.entity.SystemResourceEntity;
import vip.specimen.system.datasource.entity.SystemResourceSuffixEntity;
import vip.specimen.system.datasource.entity.SystemSaveConfigEntity;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import vip.specimen.system.result.JsonResult;
import vip.specimen.system.service.SystemResourceService;
import vip.specimen.system.service.SystemResourceSuffixService;
import vip.specimen.system.service.SystemSaveConfigService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * *@Author: 余浪人
 * *@Date：2021/3/8 14:10
 * *@Email:yulangren520@Gmail.com
 * *@QQ:1368419640
 **/
@Getter
@Setter
@Slf4j
@Component
public class QiNiuUpload implements SaveMethodInterface {
    private String bucket;
    private Auth auth;
    private String domain;
    private Configuration cfg = new Configuration(Region.autoRegion()); // 自动匹配区域
    private UploadManager uploadManager = new UploadManager(cfg);
    @Resource
    private SystemSaveConfigService saveConfigService;
    @Resource
    private SystemResourceService resourceService;
    @Resource
    private SystemResourceSuffixService resourceSuffixService;
    public static QiNiuUpload qiNiuUpload;

    @Override
    public JsonResult<SystemResourceEntity> upload(MultipartFile file) {
        String originalName = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().substring(0, 8);
        String suffix = originalName.substring(originalName.indexOf(".")).toLowerCase();
        try {
            SystemResourceSuffixEntity suffixEntity = qiNiuUpload.resourceSuffixService.findBySuffix(suffix);
            if (null == suffixEntity || !suffixEntity.isEnable() || null == suffixEntity.getKindEntity() || !suffixEntity.getKindEntity().isEnable()) {
                throw new SystemExceptionHandler(ResultCode.ERROR_UPLOAD_NOT_ALLOW);
            }
            String path = suffixEntity.getKindEntity().getPath().startsWith("/") ? suffixEntity.getKindEntity().getPath().substring(1) : suffixEntity.getKindEntity().getPath();
            String name = uuid + suffix;
            String fileName = !path.endsWith("/") ? path + "/" + name : path + name;
            Response response = qiNiuUpload.uploadManager.put(file.getInputStream(), fileName, qiNiuUpload.auth.uploadToken(qiNiuUpload.bucket), null, null);
            String resourceUrl = qiNiuUpload.domain + "/" + fileName;
            SystemResourceEntity resource = null;
            if (response.isOK()) {
                resource = qiNiuUpload.resourceService.insert(new SystemResourceEntity(name, file.getSize(), originalName, resourceUrl, file.getContentType(), suffixEntity, SaveMethodEnum.QiNiu, fileName));
            }
            return JsonResult.success(resource);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("七牛云上传文件错误:" + e.getMessage());
            throw new SystemExceptionHandler(ResultCode.ERROR_UPLOAD_FAILED);
        }
    }

    @Override
    public void download(String fileName) {

    }

    @Override
    public boolean delete(String key) {
        BucketManager bucketManager = new BucketManager(qiNiuUpload.auth, qiNiuUpload.cfg); // 七牛云删除
        try {
            bucketManager.delete(qiNiuUpload.bucket, key);
            return true;
        } catch (QiniuException ex) {
            log.error("七牛云删除异常:" + ex.getMessage());
            ex.printStackTrace();
        }
        return false;
    }

    @Override
    public List getFileList() {
        return null;
    }

    @Override
    @PostConstruct
    public void init() {
        qiNiuUpload = this;
        qiNiuUpload.resourceSuffixService = resourceSuffixService;
        qiNiuUpload.resourceService = resourceService;
        qiNiuUpload.saveConfigService = saveConfigService;
        SystemSaveConfigEntity config = qiNiuUpload.saveConfigService.getConfig();
        qiNiuUpload.bucket = config.getQiNiuSaveName();
        qiNiuUpload.auth = Auth.create(config.getQiNiuAccessKey(), config.getQiNiuSecretKey());
        qiNiuUpload.domain = config.getQiNiuDomain();
    }
}
